import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class TicTacToePanel extends JPanel{
	
	private DisplayPanel dp;
	private TTTLogic tttl;
	private JButton[][] bArray;
	public static final int ROWS = 3;
	public static final int COLS = 3;
	private int bCount = 0;
	public static boolean turn = true;
	private Font f;
	
	public TicTacToePanel(DisplayPanel dp) {
		tttl = new TTTLogic(this,dp);
		f = new Font("Arial", Font.BOLD, 50);
		this.dp = dp;
		bArray = new JButton[ROWS][COLS];
		GridLayout g = new GridLayout(ROWS,COLS);
		this.setLayout(g);
		for (int i = 0; i<ROWS; i++) {
			for (int j = 0; j<ROWS; j++) {
				bCount++;
				JButton b = new JButton("");
				b.addActionListener(new ButtonListener(bCount));
				b.setFont(f);
				bArray[i][j] = b;
				add(b);
			}
		}
		setBackground(Color.black);
		setPreferredSize(new Dimension(400,400));
	}
	
	public JButton[][] getArray() {
		return bArray;
	}
	
	private class ButtonListener implements ActionListener {
		int num;
		public ButtonListener(int num) {
			this.num = num;
		}
		public void actionPerformed(ActionEvent e) {

			if (turn) {
				((JButton)e.getSource()).setText("X");
				((JButton)e.getSource()).setEnabled(false);
				tttl.checkTie();
				if (tttl.checkWin()) {
					dp.getLabel().setText("Player 1 Wins!");
					tttl.disable();
					int ans = JOptionPane.showConfirmDialog(null, "Do you want to play again?", "Game Over!", JOptionPane.YES_NO_OPTION);
					if (ans == 0) {
						tttl.reset();
					} else {
						System.exit(0);
					}
				} else {
					dp.getLabel().setText("Player 2's Turn!");
					turn = false;
			    }
		
	        } else {
				((JButton)e.getSource()).setText("O");
				((JButton)e.getSource()).setEnabled(false);
				tttl.checkTie();
				if (tttl.checkWin()) {
					dp.getLabel().setText("Player 2 Wins!");
					tttl.disable();
					int ans = JOptionPane.showConfirmDialog(null, "Do you want to play again?", "Game Over!", JOptionPane.YES_NO_OPTION);
					if (ans == 0) {
						tttl.reset();
					} else {
						System.exit(0);
					}
				} else {
					dp.getLabel().setText("Player 1's Turn!");
					turn = true;
				}
			}
		} //end actionPerformed
	} //end ButtonListener
} //end TicTacToePanel
